package com.fan.txl.ui.adapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiajiabao on 17-1-10.
 */

public abstract class BindAdapt<Data> extends  RecyclerView.Adapter<BindAdapt.BindingVHolder> {

    public abstract int getLayoutId(int viewType);
    public abstract int getVariableId();
    public abstract void onDataBind(BindingVHolder holder, int position);

    List<Data> mData;

    public List<Data> getData() {
        return mData;
    }


    public BindAdapt(@NonNull List<Data> data) {
        mData=data;
    }

    @SuppressWarnings("unused")
    public void addList(@NonNull List<Data> data) {
        if (mData==null){
            return;
        }
        mData.addAll(data);
    }

    @SuppressWarnings("unused")
    public void addOne(@NonNull Data data) {
        if (mData==null){
            return;
        }
        mData.add(data);
    }

    @Override
    public int getItemViewType(int position) {
        Data data= mData.get(position);

        return super.getItemViewType(position);
    }

    @Override
    public BindingVHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), getLayoutId(viewType), parent, false);
        BindingVHolder holder = new BindingVHolder(binding.getRoot());
        holder.setBinding(binding);
        return holder;
    }

    @Override
    public void onBindViewHolder(BindingVHolder holder, int position) {
        Data data= mData.get(position);
        holder.getBinding().setVariable(getVariableId(),data);
        onDataBind(holder,position);
    }

    @Override
    public int getItemCount() {
        return mData==null?0:mData.size();
    }

    public static class BindingVHolder extends  RecyclerView.ViewHolder{
        private  ViewDataBinding mBinding;

        public BindingVHolder(View itemView) {
            super(itemView);
        }

        public ViewDataBinding getBinding() {
            return mBinding;
        }
        public void setBinding(ViewDataBinding binding) {
            mBinding = binding;
        }
    }
}
